/**
 * 路由管理
 */
const NAVIGATE_TO = "navigateTo"
const REDIRECT_TO = "redirectTo"
const RE_LAUNCH = "reLaunch"
var route = {

  action: NAVIGATE_TO, // 跳转方式
  url: "", // 路径
  params: [], // 参数
  reportName: "", // 上报时携带路径名

  // 回调
  callback: {
    success: function(e) {},
    fail: function(e) {},
    complete: function(e) {}
  },

  // 设置跳转方式
  setAction: function(action) {
    this.action = action;
    return this;
  },

  setUrl: function(url) {
    this.url = url;
    return this;
  },

  // 设置参数(格式为数组eg:["key1","value1","key2","value2"...])
  setParams: function(params) {
    this.params = params;
    return this;
  },

  // 设置上报时携带路径名
  setReportName: function(reportName) {
    this.reportName = reportName;
    return this;
  },

  // 设置回调
  setCallback: function(callback) {
    this.callback = callback;
    return this;
  },

  // 执行
  run: function() {
    var _this = this;
    if (_this.url != "") {
      if (_this.action == REDIRECT_TO) {
        wx.redirectTo({
          url: _this.url + "?" + formatParams(_this.params),
          fail: function(e) {
            let errMsg = e.errMsg;
            reportAnalytics("page_turn_failed", {
              error_msg: _this.reportName + "--" + errMsg
            })
          }
        })
      } else if (_this.action == RE_LAUNCH) {
        wx.reLaunch({
          url: _this.url + "?" + formatParams(_this.params),
          fail: function(e) {
            let errMsg = e.errMsg;
            reportAnalytics("page_turn_failed", {
              error_msg: _this.reportName + "--" + errMsg
            })
          }
        })
      } else {
        wx.navigateTo({
          url: _this.url + "?" + formatParams(_this.params),
          fail: function(e) {
            if (typeof _this.callback.fail == "function") {
              _this.callback.fail(e);
            }
            let errMsg = e.errMsg;
            reportAnalytics("page_turn_failed", {
              error_msg: _this.reportName + "--" + errMsg
            })
          },
          success: function(e) {
            if (typeof _this.callback.success == "function") {
              _this.callback.success(e);
            }
          },
          complete: function(e) {
            if (typeof _this.callback.complete == "function") {
              _this.callback.complete(e);
            }
          }
        })
      }
    } else {
      reportAnalytics("page_turn_failed", {
        error_msg: _this.reportName + "--url为空" + "--" + errMsg
      })
    }
  }

}

/**
 * 页面间参数处理工具
 * arr 传入数组,两两拼接成字符串
 */
const formatParams = function(arr) {
  var sb = ""
  var ar = []
  ar.length
  if (arr.length > 2) {
    for (var i = 0; i < arr.length; i++) {
      if (i == 0) {
        // 键
        sb = arr[i] + "="
      } else if (i == arr.length - 1) {
        // 值
        sb = sb + arr[i]
      } else if (i % 2 == 0) {
        // 键
        sb = sb + arr[i] + "="
      } else {
        // 值
        sb = sb + arr[i] + "&"
      }
    }
  } else {
    sb = arr[0] + "=" + arr[1]
  }
  return sb
};

// 后台自定义事件上报
function reportAnalytics(cssName, params = {}) {
  // 事件上报基础信息(用户ID,用户微信昵称)
  let reportBaseObj = {
    user_id: getUserInfo().userId,
    user_name: getApp().globalData.userInfo != undefined ? getApp().globalData.userInfo != null ? getApp().globalData.userInfo.nickName != undefined ? getApp().globalData.userInfo.nickName != null ? getApp().globalData.userInfo.nickName : "" : "" : "" : "",
  }

  // 微信后台自定义事件统计
  wx.reportAnalytics(cssName, Object.assign(reportBaseObj, params));

  // 阿拉丁统计
  getApp().aldstat.sendEvent(cssName, Object.assign(reportBaseObj, params));
}

/**
 * 用于从内存或缓存获取用户登录信息
 */
function getUserInfo() {
  let loginResult = getApp().globalData.loginResult;
  let userId;
  if (loginResult != null && loginResult != undefined) {
    userId = loginResult.userId;
  }
  if (userId != undefined && userId != null && userId != 0) {
    return loginResult;
  } else {
    try {
      loginResult = wx.getStorageSync("loginResult")
      userId = loginResult.userId
      if (userId != undefined && userId != null && userId != 0) {
        return loginResult
      } else {
        return {
          userId: 0,
          mobile: "",
          userToken: ""
        }
      }
    } catch (e) {
      return {
        userId: 0,
        mobile: "",
        userToken: ""
      }
    }
  }
}

module.exports = {
  route: route,
  NAVIGATE_TO: "navigateTo",
  REDIRECT_TO: "redirectTo",
  RE_LAUNCH: "reLaunch"
}